package com.MusicWeb.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@WebServlet("/download_new")
public class DownloadUserServlet extends HttpServlet {
    private String dirPath;

    @Override
    public void init() throws ServletException {
        super.init();
        dirPath = this.getServletContext().getInitParameter("uploadDir");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = req.getParameter("n");
        // 打开文件的输入流
        FileInputStream fis = new FileInputStream(dirPath + fileName);
        // 打开响应的输出流
        ServletOutputStream sos = resp.getOutputStream();
        //下载文件的地方
        String newName=req.getParameter("title");
        FileOutputStream fos = new FileOutputStream(dirPath + newName);
        // 把输入流的内容搬运到输出流内
        byte[] bytes = new byte[1024];
        int len;
        while ((len = fis.read(bytes)) > 0) {
            sos.write(bytes, 0, len);
        }
        // 刷新并关闭输入输出流
        sos.flush();
        sos.close();
        fis.close();
    }
}
